package com.example.wanghao.wangyixinwen.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.wanghao.wangyixinwen.R;

import java.util.List;


/**
 * Created by wanghao on 2016/5/21.
 */
public class RollViewPager extends ViewPager {
    private  List<ImageView> mDots;//点的集合
    private List<String> mTitles;//标题数据聚合
    private TextView tv_title;//显示标题的文本控件
    private List<String> mImages;//热门新闻的图片地址
    private RollAdapter mAdapter;

    private int pravousPosition;//用来记录前一个点的选中位置

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //获取当前界面的索引
            int currentItem = RollViewPager.this.getCurrentItem();
            int pos = (currentItem+1)%mImages.size();
            //让viewpager切换下一个界面
            RollViewPager.this.setCurrentItem(pos,false);

            mHandler.sendEmptyMessageDelayed(0,2000);
        }
    };
    private int mStartX;
    private int mStartY;
    private long mCurrentTimeMillis;
    private OnClickListener mOnClickItemListener;//点击事件接口回调


    public RollViewPager(final Context context) {
        super(context);
        this.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //修改标题
                tv_title.setText(mTitles.get(position));
                //修改对应点的选中状态
                mDots.get(pravousPosition).setImageResource(R.drawable.dot_normal);
                pravousPosition = position;
                mDots.get(position).setImageResource(R.drawable.dot_focus);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        //自动轮播停止
                        mHandler.removeCallbacksAndMessages(null);
                        mCurrentTimeMillis = System.currentTimeMillis();
                        break;
                    case MotionEvent.ACTION_UP:
                        //自动轮播开始
                        mHandler.sendEmptyMessageDelayed(0,2000);
                        long upTime = System.currentTimeMillis();
                        //手指按下和手指抬起时间间隔小于500毫秒,认为是点击事件
                        if ((upTime - mCurrentTimeMillis) < 500){
                            mOnClickItemListener.onClick();
                        }
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        mHandler.sendEmptyMessageDelayed(0,2000);
                        break;
                }
                return false;
            }
        });

    }

    public RollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RollViewPager(Context context, List<ImageView> dots) {
        this(context);
        this.mDots = dots;
    }

    public void setTitles(List<String> newsTitles, TextView top_news_title) {
        //1.记录数据和控件
        this.mTitles = newsTitles;
        this.tv_title = top_news_title;

        //2.设置默认的标题
        this.tv_title.setText(this.mTitles.get(0));
    }

    public void setImages(List<String> images) {
        this.mImages = images;
    }

    public void start() {
        //给轮播图设置适配器进行展示
        if (mAdapter == null) {
            mAdapter = new RollAdapter();
            this.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }

        //自动轮播
        mHandler.sendEmptyMessageDelayed(0,2000);

    }

    //把消息循环清除掉
    public void stop() {
        mHandler.removeCallbacksAndMessages(null);
    }

    private class RollAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mImages.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView view = (ImageView) View.inflate(getContext(), R.layout.viewpager_item, null);
            Glide.with(getContext().getApplicationContext()).load(mImages.get(position)).into(view);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    //事件分发
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                mStartX = (int) ev.getX();
                mStartY = (int) ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                int endX = (int) ev.getX();
                int endY = (int) ev.getY();
                int diffX = endX - endY;
                int diffY = endY - endX;
                if (Math.abs(diffX) > Math.abs(diffY)){
                    //请求父控件不拦截我
                    getParent().requestDisallowInterceptTouchEvent(true);
                }else {
                    //父控件想拦截就拦截
                    getParent().requestDisallowInterceptTouchEvent(false);
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

  public void setOnClickItemListener(OnClickListener listener){
      this.mOnClickItemListener = listener;
  }
    //点击事件的接口回调
  public interface OnClickListener{
        public void onClick();
    }
}

